<?php declare(strict_types=1);

namespace App\Api\V2\Controller\Merchant;

use App\Api\Controllers\BaseController;
use App\Models\CommonConfigs;
use App\Models\QuotaConfig;
use App\Services\Pay\GuoTonXinYi\Pay;
use App\Services\PrintSqlService;
use App\Services\Quota\GtxyQuotaService;
use App\Traits\ResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class QuotaController extends BaseController
{
    use ResponseTrait;

    public function getQuota(Request $request)
    {
        $mch_id = $request->input("mch_id");
        $company = $request->input("company", "gtxy");
        try {
            if (empty($mch_id)) {
                throw new \Exception("商户号参数不能为空");
            }
            $mch_ids = explode(",", $mch_id);
            $config = CommonConfigs::query()->where("config_id", "1234")->first();
            if (empty($config)) {
                throw new \Exception("配置不存在");
            }
            $companyRuleId = DB::table('company_rule')->where(['code' => $company])->value('id');
            $result = [];
            foreach ($mch_ids as $mch_no) {
                $quotalArr = GtxyQuotaService::getInstance()->getQuota($mch_no, [
                    "key" => $config->public_key,
                    "orgId" => $config->platform_id,
                    "company" => $company
                ]);
                if (empty($quotalArr["quota"])) {
                    continue;
                }
                /**
                 * company_code:"easypaya"
                 * company_rule_id:42
                 * end_date:"20250605"
                 * mch_id:"531000022263097"
                 * quota:151.18000000000006
                 * start_date:"20250520"
                 */
                $quotaConfig = QuotaConfig::query()->where("mch_id", $mch_no)->where("company", $company)->first();
                $result[] = [
                    "company_code" => $company,
                    "company_rule_id" => $companyRuleId,
                    "end_date" => $quotalArr["end_date"],
                    "mch_id" => $mch_no,
                    "quota" => $quotalArr["quota"],
                    "start_date" => $quotalArr["start_date"],
                    "quota_rate" => empty($quotaConfig) ? 0 : $quotaConfig->quota_rate,
                    "bank_name" => empty($quotaConfig) ? "" : $quotaConfig->bank_name
                ];
            }
            return $this->successResponse("ok", ["data" => $result]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }

    }
}